const { ipcMain, BrowserWindow } = require('electron');
// const {pinyin} = require("pinyin");

const getSource = () => {
    ipcMain.handle('on-url-server', (e, url) => {
        return new Promise((resolve,reject) => {
            const win = new BrowserWindow({
                width: 1920,
                height: randomHeight(),
                show: false,    // 不展示
                webPreferences: {
                    offscreen:true , // 窗口在内存中使用
                }
            })
            win.loadURL(url);
    
            // 网页加载完成
            win.webContents.on('did-finish-load', async () => {
                const title = win.getTitle();
                try {
                    // nativeImage
                    const image = await win.webContents.capturePage();
                    const screenshot = image.toDataURL();   // 转成base64的图片
                    resolve({
                        title,
                        titleEn:'',//convertToPinyin(title),
                        screenshot,
                        url,
                    });
                    // 加载完成后关闭内存中窗口
                    if (screenshot && win) {
                        // 调用 destroy 方法来关闭窗口并释放内存
                        win.destroy();
                    }
                }
                catch (e) {
                    console.log(e);
                    reject(e);
                }
            });
        })
    })
};

function randomHeight(max = 1200, min = 500) {
    return Math.floor(Math.random() * (max - min) + min);
}


// function convertToPinyin(text) {
//     const options = {
//       style: 'normal', // 普通风格，不带声调
//       heteronym: false // 无多音字模式
//     };
   
//     const result = pinyin(text, options).join('');
   
//     return result;
//   }
                          

module.exports = getSource